<template>
  <div class="ManageDeveloper">
    <div class="headerBox">
      <el-button type="primary" @click="dialogVisible = true">新增团队成员</el-button>
      <el-input v-model="inputValue" placeholder="请输入搜索关键词" /><el-button
        type="primary"
        @click="searchKey"
        >搜索</el-button
      >
    </div>
    <div class="headerBox">
      <el-radio-group v-model="radio">
        <el-radio>全部岗位</el-radio>
        <el-radio :label="2">开发人员</el-radio>
        <el-radio :label="3">测试人员</el-radio>
      </el-radio-group>
    </div>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="用户名">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.username }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="密码">
        <template #default="scope">
          {{ scope.row.userpwd }}
        </template>
      </el-table-column>
      <el-table-column label="岗位名称">
        <template #default="scope">
          {{ scope.row.type == 1 ? '项目经理' : scope.row.type == 2 ? '开发人员' : '测试人员' }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <div>
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" title="新增团队成员" width="30%">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="岗位">
          <el-select v-model="posts" placeholder="请选择员工岗位">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">新增</el-button>
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <br />
    <div class="demo-pagination-block">
      <el-pagination
        @change="change"
        v-model:current-page="pageindex"
        v-model:page-size="pageNum"
        background
        layout="prev, pager, next"
        :total="total"
      />
    </div>

    <el-dialog v-model="editDialogVisible" title="编辑资料" width="30%">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="岗位">
          <el-select v-model="Editposts" :placeholder="tipType">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="用户名" prop="Editusername">
          <el-input v-model="Editusername" />
        </el-form-item>
        <el-form-item label="密码" prop="Edituserpwd">
          <el-input v-model="Edituserpwd" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, watch } from 'vue'
import {
  userQuery,
  userAdd,
  userDel,
  userInsertMany,
  userUpdate,
  userManageQuery
} from '../services/userService'
import { menuQuery } from '../services/menuService'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { importsExcel } from '../util/excel'

// 分页
let pageindex = ref(1) //显示第几页
let pageNum = ref(5) //每页显示数据
let total = ref() //数据总数

interface User {
  _id?: string
  username: string
  userpwd: string
  type: number
}

// 分类
let radio: any = ref()
let inputValue = ref('')
watch([radio], async () => {
  let keyValue = inputValue.value
  let res = await userManageQuery({
    keyValue,
    type: radio.value,
    pageindex: pageindex.value,
    pageNum: pageNum.value
  })
  tableData.value = res.data.data
  total.value = res.data.total
})

// 搜索
let searchKey = async () => {
  let keyValue = inputValue.value
  let res = await userManageQuery({
    type: radio.value,
    keyValue,
    pageindex: pageindex.value,
    pageNum: pageNum.value
  })
  tableData.value = res.data.data
  total.value = res.data.total
}
watch([inputValue], () => {
  if (!inputValue.value) {
    search()
  }
})

// 分页按钮改变
let change = async (index: number) => {
  pageindex.value = index //页面的改变
  let keyValue = inputValue.value
  let res = await userManageQuery({
    type: radio.value,
    keyValue,
    pageindex: pageindex.value,
    pageNum: pageNum.value
  })
  tableData.value = res.data.data
  total.value = res.data.total
}

// 编辑
let editDialogVisible = ref<boolean>(false)
let tipType: any = ref('')
let Editposts: any = ref('')
let EditId: any = ref('')
let Editusername = ref('')
let Edituserpwd = ref('')

// 岗位
let posts = ref('')
const options = ref<any>([])

let dialogVisible = ref<boolean>(false) //控制弹框显示
const tableData = ref<Array<User>>([])

const ruleFormRef = ref<FormInstance>() //表单元素
const ruleForm = reactive({
  //表单的路由
  //数据
  username: ''
})

const validateUsername = (rule: any, value: any, callback: any) => {
  if (value.length >= 4 && value.length <= 10) {
    callback()
  } else {
    callback(new Error('用户名长度只能是4~10位'))
  }
}
const rules = reactive<FormRules<typeof ruleForm>>({
  //规格
  username: [{ validator: validateUsername, trigger: 'blur' }]
})

let search = async () => {
  let res = await userQuery({ type: [2, 3], pageindex: pageindex.value, pageNum: pageNum.value }) //做查询
  tableData.value = res.data.data
  total.value = res.data.total

  // 新增岗位类目
  let res2 = await menuQuery({})
  options.value = res2.data.manageTypeList.map((item: any) => {
    return { label: item.name, value: item.type }
  })
}
onMounted(async () => {
  search()
})

//编辑事件
const handleEdit = (index: number, row: User) => {
  editDialogVisible.value = true
  EditId.value = row._id
  Editusername.value = row.username
  Edituserpwd.value = row.userpwd
  tipType.value = row.type == 2 ? '开发人员' : '测试人员'
}

//删除事件
const handleDelete = async (index: number, row: User) => {
  let _id = row._id
  let res = await userDel({
    _id
  })
  if (res.data.code == 200) {
    tableData.value = tableData.value.filter((item) => {
      return item._id != _id
    })
  }
  ElMessage(res.data.msg)
}

//新增员工
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      if (!editDialogVisible.value) {
        let res = await userAdd({
          username: ruleForm.username,
          userpwd: '123456',
          type: posts.value
        })
        ElMessage(res.data.msg)
        if(res.data.code == 200){
          tableData.value.push(res.data.data[0]) //数据同步到列表
        }
        formEl.resetFields()
        dialogVisible.value = false
        posts.value = ''
      } else {
        // 更新
        if (Editposts.value) {
          let res2 = await userUpdate({
            username: Editusername.value,
            userpwd: Edituserpwd.value,
            _id: EditId.value,
            type: Editposts.value
          })
          ElMessage(res2.data.msg)
          formEl.resetFields()
          editDialogVisible.value = false
          Editposts.value = ''
          // 同步
          tableData.value.forEach((item: any) => {
            if (item._id == EditId.value) {
              item.type = res2.data.userData[0].type
              item.username = res2.data.userData[0].username
              item.userpwd = res2.data.userData[0].userpwd
            }
          })
        } else {
          let res2 = await userUpdate({
            username: Editusername.value,
            userpwd: Edituserpwd.value,
            _id: EditId.value
          })
          ElMessage(res2.data.msg)
          formEl.resetFields()
          editDialogVisible.value = false
          Editposts.value = ''
          // 同步
          tableData.value.forEach((item: any) => {
            if (item._id == EditId.value) {
              item.username = res2.data.userData[0].username
              item.userpwd = res2.data.userData[0].userpwd
            }
          })
        }
      }
    } else {
      return false
    }
  })
}
//取消
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogVisible.value = false
  editDialogVisible.value = false
}

let downFile = () => {
  setTimeout(() => {
    let url = '/api/template/学生信息模版.xlsx'
    let a = document.createElement('a')
    a.href = url
    a.click()
    a.remove()
  }, 2000) //两秒以后下载
}
let getExcelData = async (e: any) => {
  let res = await importsExcel(e)
  console.log(res)

  let res2 = await userInsertMany({
    list: res
  })

  if (res2.data.code == 200) {
    // tableData.value.push(...res2.data.data);
    pageindex.value = 1 //默认第一页
    search()
  } else if (res2.data.code == 201) {
    alert('以下用户名存在' + res2.data.data.join('|'))
  }
}
</script>
<style lang="scss" scoped>
.ManageDeveloper {
  margin-top: 10px;
}
.headerBox {
  padding: 10px 5px 5px;
  display: flex;
  .el-input {
    margin: 0 10px;
  }
}
</style>
